package com.hdu;


import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;


/**
 * 哲学家就餐问题
 */
public class PhilosophersDiningProblem {

    public static void main(String[] args) {

        // 创建5只筷子
        Chopstick[] chopsticks = new Chopstick[5];
        for (int i = 0; i < 5; i++) {
            chopsticks[i] = new Chopstick(i + "");
        }

        // 创建五个哲学家
        Philosopher[] philosophers = new Philosopher[5];
        for (int i = 0; i < 5; i++) {
            philosophers[i] = new Philosopher(chopsticks[i], chopsticks[(i + 1) % 5], i + "号哲学家");
        }


        for (int i = 0; i < 5; i++) {
            philosophers[i].start();
        }
    }

}


@Slf4j
class Philosopher extends Thread {

    private final Chopstick left;
    private final Chopstick right;
    private final String identity;

    public Philosopher(Chopstick left, Chopstick right, String identity) {
        this.left = left;
        this.right = right;
        this.identity = identity;
    }

    @Override
    public void run() {
        while (true) {
            eat();
        }
    }


    void eat() {
        if (left.tryLock()) {
            try {
                if (right.tryLock()) {
                    try {
                        log.info("哲学家 : {}, 开始吃饭", identity);
                        TimeUnit.MILLISECONDS.sleep(500);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    } finally {
                        right.unlock();
                    }
                }
            } finally {
                left.unlock();
            }
        }
    }
}

class Chopstick extends ReentrantLock {


    private final String identity;

    public Chopstick(String identity) {
        this.identity = identity;
    }
}
